package com.cmol.peopledetectapp.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.cmol.data.GlobalData;
import com.cmol.net.Network;
import com.cmol.peopledetectapp.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 人脸识别验证/登录
 *
 * @author 张瀚文
 */
public class FaceRecognitionActivity extends AppCompatActivity {


    final int TAKE_PHOTO = 1;
    /**
     * 界面提交按钮
     */
    private Button photoButton, submitButton;
    /**
     * 人脸图片
     */
    private ImageView photoImage;
    /**
     * 图片地址
     */
    private Uri imageUri;
    /**
     * 调用类型（true：注册，false：登录
     */
    private String type = new String();
    /**
     * 用户身份识别
     */
    private String userId = new String();
    /**
     * 响应服务器消息
     */
    private boolean isSucces = false;
    /**
     * 图片输出
     */
    private File output;
    /**
     * 通信模块
     */
    private Network network;
    private OutputStream os = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facerecognition);

        photoButton = findViewById(R.id.button15);
        submitButton = findViewById(R.id.SubmitButton);
        photoImage = findViewById(R.id.imageView3);
    }

    /**
     * 提交按钮点击事件
     *
     * @param view
     */
    public void SubmitClick(View view) {
        Intent thisIntent = getIntent();
        type = thisIntent.getStringExtra("type");

        // 判断调用类型
        if (type.equals("1")) {
            // 注册
            // 将人脸信息传回注册界面
            if (output == null) {
                Toast.makeText(FaceRecognitionActivity.this, "请先拍照", Toast.LENGTH_SHORT).show();
            } else {
                // image文件转成byte数组

//                Intent intent = new Intent(this,RegisterActivity.class);
//                startActivity(intent);
                finish();
            }
        } else {
            // 登录
            // 联网获取登录账户或报错(传输File文件output,读取返回结果)
            JSONObject tmp = new JSONObject();
            try {
                tmp.put("image", output);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            network = new Network(tmp, "/user/sendFeedBack") {
                @Override
                protected void process(Call call, Response response) throws IOException {
                    String ans = Objects.requireNonNull(response.body()).string().trim();
                    try {
                        JSONObject js = new JSONObject(ans);
                        // 接收服务器反馈的成功信息
                        isSucces = js.getBoolean("auth");
                        userId = js.getString("token");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void failureWarn() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FaceRecognitionActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            };

            if (isSucces == true) {
                GlobalData.setCurrentUserAccount(Integer.parseInt(userId));
                Toast.makeText(FaceRecognitionActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MapActivity.class));
                finish();
            } else {
                Toast.makeText(FaceRecognitionActivity.this, "验证失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 拍照按钮点击事件
     *
     * @param view
     */
    public void PhotographClick(View view) {
        /**
         * 设置图片输出格式
         */
        output = new File(getExternalCacheDir(), "output_image.jpg");

        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= 24) {
            /**
             * 设置图片保存路径
             */
            imageUri = FileProvider.getUriForFile(FaceRecognitionActivity.this, "com.example.takephoto.fileprovider", output);
        } else {
            imageUri = Uri.fromFile(output);
        }
        /**
         * 调用系统拍照功能
         */
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        /**
                         * 保存拍摄的图片
                         */
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        photoImage.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}